import React, { useState, useEffect } from 'react'
import { Card, List, Avatar, Button, Input, Tag, message, Modal, Form, Select } from 'antd'
import { useNavigate } from 'react-router-dom'
import { MessageOutlined, LikeOutlined, ShareAltOutlined, UserOutlined, PlusOutlined, ArrowLeftOutlined } from '@ant-design/icons'

const { TextArea } = Input
const { Option } = Select

interface TechPost {
  id: string
  title: string
  content: string
  author: string
  avatar: string
  timestamp: string
  likes: number
  comments: number
  shares: number
  tags: string[]
  category: string
  isLiked: boolean
}

const TechExchange: React.FC = () => {
  const navigate = useNavigate()
  const [posts, setPosts] = useState<TechPost[]>([])
  const [loading, setLoading] = useState(true)
  const [isModalVisible, setIsModalVisible] = useState(false)
  const [newPostForm] = Form.useForm()

  useEffect(() => {
    fetchTechPosts()
  }, [])

  const fetchTechPosts = async () => {
    setLoading(true)
    try {
      // 模拟技术交流帖子数据
      const mockPosts: TechPost[] = [
        {
          id: '1',
          title: '水稻高产栽培技术分享',
          content: '近年来通过实践总结了一套水稻高产栽培技术，包括选种、育苗、田间管理等方面，亩产可达600公斤以上。',
          author: '张技术员',
          avatar: '',
          timestamp: '2024-03-16 14:30',
          likes: 24,
          comments: 8,
          shares: 3,
          tags: ['水稻', '栽培技术', '高产'],
          category: '种植技术',
          isLiked: false
        },
        {
          id: '2',
          title: '智能灌溉系统在果园的应用',
          content: '介绍我们果园采用的智能灌溉系统，通过传感器实时监测土壤湿度，自动调节灌溉量，节水30%以上。',
          author: '李果农',
          avatar: '',
          timestamp: '2024-03-15 09:15',
          likes: 18,
          comments: 12,
          shares: 5,
          tags: ['智能灌溉', '果园', '节水'],
          category: '智能农业',
          isLiked: true
        },
        {
          id: '3',
          title: '有机蔬菜病虫害防治经验',
          content: '分享有机蔬菜种植过程中常见的病虫害防治方法，使用生物农药和物理防治手段，确保蔬菜安全无污染。',
          author: '王菜农',
          avatar: '',
          timestamp: '2024-03-14 16:45',
          likes: 32,
          comments: 15,
          shares: 7,
          tags: ['有机蔬菜', '病虫害', '生物防治'],
          category: '种植技术',
          isLiked: false
        },
        {
          id: '4',
          title: '温室大棚智能化改造方案',
          content: '详细介绍传统温室大棚的智能化改造方案，包括环境监控、自动通风、智能补光等系统集成。',
          author: '赵工程师',
          avatar: '',
          timestamp: '2024-03-13 11:20',
          likes: 21,
          comments: 9,
          shares: 4,
          tags: ['温室大棚', '智能化', '环境监控'],
          category: '设施农业',
          isLiked: false
        },
        {
          id: '5',
          title: '农产品电商销售技巧',
          content: '分享农产品电商平台运营经验，包括产品包装、物流配送、客户服务等方面的实用技巧。',
          author: '陈电商',
          avatar: '',
          timestamp: '2024-03-12 13:10',
          likes: 28,
          comments: 11,
          shares: 6,
          tags: ['电商', '农产品销售', '运营技巧'],
          category: '电商营销',
          isLiked: true
        }
      ]

      setPosts(mockPosts)
    } catch (error) {
      message.error('获取技术交流帖子失败')
    } finally {
      setLoading(false)
    }
  }

  const handleLike = (postId: string) => {
    setPosts(posts.map(post => 
      post.id === postId 
        ? { 
            ...post, 
            likes: post.isLiked ? post.likes - 1 : post.likes + 1,
            isLiked: !post.isLiked 
          }
        : post
    ))
  }

  const handleNewPost = async (values: any) => {
    try {
      const newPost: TechPost = {
        id: Date.now().toString(),
        title: values.title,
        content: values.content,
        author: '当前用户',
        avatar: '',
        timestamp: new Date().toLocaleString('zh-CN'),
        likes: 0,
        comments: 0,
        shares: 0,
        tags: values.tags || [],
        category: values.category,
        isLiked: false
      }

      setPosts([newPost, ...posts])
      setIsModalVisible(false)
      newPostForm.resetFields()
      message.success('发布成功')
    } catch (error) {
      message.error('发布失败')
    }
  }

  const getCategoryColor = (category: string) => {
    switch (category) {
      case '种植技术': return 'green'
      case '智能农业': return 'blue'
      case '设施农业': return 'orange'
      case '电商营销': return 'purple'
      default: return 'default'
    }
  }

  return (
    <div style={{ padding: '24px', background: '#f5f5f5', minHeight: '100vh' }}>
      <Card 
        title={
          <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
            <Button 
              type="text" 
              icon={<ArrowLeftOutlined />} 
              onClick={() => navigate('/user-dashboard')}
              style={{ padding: '4px 8px' }}
            >
              返回
            </Button>
            <span>技术交流社区</span>
          </div>
        }
        extra={
          <Button 
            type="primary" 
            icon={<PlusOutlined />}
            onClick={() => setIsModalVisible(true)}
          >
            发布新帖
          </Button>
        }
        style={{ marginBottom: '24px' }}
      >
        {/* 搜索和筛选 */}
        <div style={{ marginBottom: '24px', display: 'flex', gap: '12px' }}>
          <Input.Search 
            placeholder="搜索技术话题..." 
            style={{ width: 300 }}
            onSearch={(value) => console.log('搜索:', value)}
          />
          <Select placeholder="选择分类" style={{ width: 120 }}>
            <Option value="all">全部</Option>
            <Option value="planting">种植技术</Option>
            <Option value="smart">智能农业</Option>
            <Option value="facility">设施农业</Option>
            <Option value="ecommerce">电商营销</Option>
          </Select>
        </div>

        {/* 帖子列表 */}
        <List
          loading={loading}
          itemLayout="vertical"
          dataSource={posts}
          renderItem={(post) => (
            <List.Item
              key={post.id}
              actions={[
                <Button 
                  type="text" 
                  icon={<LikeOutlined style={{ color: post.isLiked ? '#1890ff' : undefined }} />}
                  onClick={() => handleLike(post.id)}
                >
                  {post.likes}
                </Button>,
                <Button type="text" icon={<MessageOutlined />}>
                  {post.comments}
                </Button>,
                <Button type="text" icon={<ShareAltOutlined />}>
                  {post.shares}
                </Button>
              ]}
            >
              <List.Item.Meta
                avatar={
                  <Avatar 
                    icon={<UserOutlined />} 
                    src={post.avatar}
                    style={{ backgroundColor: '#87d068' }}
                  />
                }
                title={
                  <div>
                    <span style={{ fontSize: '16px', fontWeight: 600 }}>{post.title}</span>
                    <Tag color={getCategoryColor(post.category)} style={{ marginLeft: '8px' }}>
                      {post.category}
                    </Tag>
                  </div>
                }
                description={
                  <div>
                    <span>{post.author}</span>
                    <span style={{ marginLeft: '16px', color: '#999' }}>{post.timestamp}</span>
                  </div>
                }
              />
              <div style={{ margin: '12px 0' }}>
                {post.content}
              </div>
              <div>
                {post.tags.map(tag => (
                  <Tag key={tag} color="blue" style={{ marginBottom: '4px' }}>
                    {tag}
                  </Tag>
                ))}
              </div>
            </List.Item>
          )}
        />
      </Card>

      {/* 发布新帖模态框 */}
      <Modal
        title="发布技术交流帖子"
        open={isModalVisible}
        onCancel={() => {
          setIsModalVisible(false)
          newPostForm.resetFields()
        }}
        footer={null}
        width={600}
      >
        <Form
          form={newPostForm}
          layout="vertical"
          onFinish={handleNewPost}
        >
          <Form.Item
            name="title"
            label="标题"
            rules={[{ required: true, message: '请输入标题' }]}
          >
            <Input placeholder="请输入帖子标题" />
          </Form.Item>
          
          <Form.Item
            name="category"
            label="分类"
            rules={[{ required: true, message: '请选择分类' }]}
          >
            <Select placeholder="请选择分类">
              <Option value="种植技术">种植技术</Option>
              <Option value="智能农业">智能农业</Option>
              <Option value="设施农业">设施农业</Option>
              <Option value="电商营销">电商营销</Option>
            </Select>
          </Form.Item>
          
          <Form.Item
            name="content"
            label="内容"
            rules={[{ required: true, message: '请输入内容' }]}
          >
            <TextArea 
              rows={6} 
              placeholder="请输入帖子内容"
              showCount 
              maxLength={1000}
            />
          </Form.Item>
          
          <Form.Item
            name="tags"
            label="标签"
          >
            <Select 
              mode="tags" 
              placeholder="添加标签（可选）"
              style={{ width: '100%' }}
            />
          </Form.Item>
          
          <Form.Item>
            <div style={{ display: 'flex', gap: '12px', justifyContent: 'flex-end' }}>
              <Button onClick={() => {
                setIsModalVisible(false)
                newPostForm.resetFields()
              }}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                发布
              </Button>
            </div>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default TechExchange